/**
 * Title : Base Dict Class Description : here Description is the function of
 * class, here maybe multirows
 */

package com.pcbly.web.components.utils;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.*;
import javax.naming.directory.*;

@SuppressWarnings("unchecked")
public class ADConnection
{
	private DirContext ldapContext;

	
	private NamingEnumeration answer;

	private static final String serverIP = ResourceBundle.getBundle("ldap").getString("server.id");
	
	private SearchControls ctls = null;
	private String filter = null;
	private String base = null;
	
	
	public ADConnection()
	{
		ctls = new SearchControls();
		ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);
		filter = "(&(ou=*))";
		base = "DC=china,DC=freeborders";
	}

	private DirContext authentication(String username, String password)
	{
		try
		{
			Hashtable ldapEnv = new Hashtable(11);
			ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
			ldapEnv.put(Context.PROVIDER_URL, "ldap://" + serverIP + ":389");

			if(username != null && !"".equals(username))
			{
				ldapEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
				ldapEnv.put(Context.SECURITY_PRINCIPAL, username + "@china.freeborders");
				ldapEnv.put(Context.SECURITY_CREDENTIALS, password);
			}
			ldapContext = new InitialDirContext(ldapEnv);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return ldapContext;
	}

	public String searchEmployeeNumber(String username, String password)
	{
		String employeeNumber = "";

		ldapContext = authentication(username,password);
		if(ldapContext != null)
		{
			try
			{
				answer = ldapContext.search(base, filter, ctls);

				while(answer.hasMore())
				{
					SearchResult sr = (SearchResult)answer.next();

					String newBase = sr.getName() + "," + base;
					String newfliter = "(&(objectclass=user)(mail=" + username + "@china.freeborders))";

					NamingEnumeration answer = null;
					answer = ldapContext.search(newBase, newfliter, ctls);

					while(answer.hasMore())
					{
						SearchResult newsr = (SearchResult)answer.next();
						Attributes newattrib = newsr.getAttributes();
						employeeNumber = newattrib.get("company").get().toString();
					}

					if(!"".equals(employeeNumber))
					{
						break;
					}
				}
				ldapContext.close();
			}
			catch(NamingException e)
			{
				e.printStackTrace();
			}
		}
		return employeeNumber;
	}

	public String searchEmail(String employeeno)
	{
		String email = "";
		String user = ResourceBundle.getBundle("ldap").getString("username");
		String psw = ResourceBundle.getBundle("ldap").getString("password");
		
		ldapContext = authentication(user,psw);
		
		if(ldapContext != null)
		{
			try
			{
				answer = ldapContext.search(base, filter, ctls);
				
				while(answer.hasMore())
				{
					SearchResult sr = (SearchResult)answer.next();

					String newBase = sr.getName() + "," + base;
					String newfliter = "(&(objectclass=user)(company=" + employeeno + "))";

					NamingEnumeration answer = null;
					answer = ldapContext.search(newBase, newfliter, ctls);

					while(answer.hasMore())
					{
						SearchResult newsr = (SearchResult)answer.next();
						Attributes newattrib = newsr.getAttributes();
						email = newattrib.get("mail").get().toString();
					}
					if(!("".equals(email)))
					{
						ldapContext.close();
						break;
					}
				}
				ldapContext.close();
			}
			catch(NamingException e)
			{
				e.printStackTrace();
			}
		}
		return email;
	}
	
	public boolean checkEmail(String nickName)
	{
		String user = ResourceBundle.getBundle("ldap").getString("username");
		String psw = ResourceBundle.getBundle("ldap").getString("password");
		String extEmail = ResourceBundle.getBundle("ldap").getString("email.ext");
		
		ldapContext = authentication(user,psw);
		
		if(ldapContext != null)
		{
			try
			{
				answer = ldapContext.search(base, filter, ctls);
				
				while(answer.hasMore())
				{
					SearchResult sr = (SearchResult)answer.next();

					String newBase = sr.getName() + "," + base;
					String newfliter = "(&(objectclass=user)(mail=" + nickName + extEmail + "))";

					String email = doFilter(newBase, newfliter, "mail");
					if( null != email )
					{
						return true;
					}
				}
				ldapContext.close();
			}
			catch(NamingException e)
			{
				e.printStackTrace();
			}
		}
		return false;
	}
	
	public String doFilter(String newBase, String newFilter, String property)
	{
		try
		{
			NamingEnumeration enumeration = ldapContext.search(newBase, newFilter, ctls);
			String temp = null;
			
			while(enumeration.hasMore())
			{
				SearchResult newsr = (SearchResult)enumeration.next();
				Attributes newattrib = newsr.getAttributes();
				temp = newattrib.get(property).get().toString();
			}
			if(null != temp && (!"".equals(temp)))
			{
				return temp;
			}
		}
		catch(NamingException e)
		{
			e.printStackTrace();
		}
		
		return null;
	}
	
	public static void main(String[] args)
	{
		ADConnection adc = new ADConnection();
		System.out.println(adc.checkEmail("randall.liu"));
	}
}
